package dev.hxliu.cn.inject;


import lombok.Getter;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.time.LocalDateTime;

@Getter
public enum InjectMethodEnum {
    // TODO bean对象获取

    //    GET_BEAN(SpringContextUtils::getBean),
    // 反射new对象
    NEW_INSTANCE((clazz)-> clazz.getDeclaredConstructor().newInstance()),
    METHOD_HANDLE((clazz)->{
        MethodHandles.Lookup lookup = MethodHandles.publicLookup();
        // 2. 定义构造函数的签名
        MethodType constructorType = MethodType.methodType(void.class);
        // 3. 查找构造函数
            MethodHandle constructorHandle = lookup.findConstructor(
                    clazz,       // 目标类
                    constructorType     // 方法签名
            );
            return (InjectMethod<?>) constructorHandle.invoke();
    })
    ;

    @FunctionalInterface
    public interface CheckedFunction<T, R> {
        /**
         * Run the Function
         *
         * @param t T
         * @return R R
         * @throws Throwable CheckedException
         */
        R apply( T t) throws Throwable;

    }


    private final CheckedFunction<Class<? extends InjectMethod<?>> ,InjectMethod<?>> convertType;

    public CheckedFunction<Class<? extends InjectMethod<?>>, InjectMethod<?>> getConvertType() {
        return convertType;
    }

    InjectMethodEnum(
             CheckedFunction<Class<? extends InjectMethod<?>>, InjectMethod<?>> convertType) {
        this.convertType = convertType;
    }

    public static class  NOW implements InjectMethod<LocalDateTime>{

        @Override
        public LocalDateTime inject() {
            return LocalDateTime.now();
        }
    }

}
